<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in getList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="filersort">筛选</el-button>
            <el-button type="info" size="small" @click="replacement">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="dialogVisible=true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
<el-dialog
  title="发表文章"
  fullscreen
  :visible.sync="dialogVisible"
  width="30%"
  :before-close="handleClose">

<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
  <el-form-item label="文章名称" prop="title">
    <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
  </el-form-item>

  <el-form-item label="文章类型" prop="cate_id" >
    <el-select v-model="ruleForm.cate_id" placeholder="请选择活动区域" style="width: 100%;">
      <el-option v-for="item in getList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
    </el-select>
  </el-form-item>

<el-form-item prop="content" label="文章内容">
<quill-editor v-model="ruleForm.content "
                @blur="$refs.ruleForm.validateField('content')">
  </quill-editor>
</el-form-item>

<el-form-item label="文章封面" prop="cover_img">
  <!-- 用来显示封面的图片 -->
  <img  v-if="picture" :src="picture" class="cover-img" ref="imgRef" />
  <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
  <br />
  <!-- 文件选择框，默认被隐藏 -->
  <input v-if="dialogVisible" type="file" style="display: none;" accept="image/*" ref="iptFile" @change="getImg"/>
  <!-- 选择封面的按钮 -->
  <el-button type="primary" @click="$refs.iptFile.click() ">+ 选择封面</el-button>
</el-form-item>

  <el-form-item prop="state">
    <el-button type="primary" @click="hSubmit('已发布') ">发布</el-button>
    <el-button type="info"  @click="hSubmit('草稿')">存为草稿</el-button>
  </el-form-item>
</el-form>

</el-dialog>
      <!-- 分页区域 -->
       <el-table
         border
        stripe
      :data="articleLists"
      style="width: 100%">
      <el-table-column prop="title" label="文章标题">
        <template v-slot=" {row} ">
           <el-link type="primary" @click="articleDetails(row.id) "> {{row.title}} </el-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="cate_name"
        label="文章分类">
      </el-table-column>
      <el-table-column
        label="发布时间">
        <template v-slot=" {row} ">
          {{formDate(row.pub_date)}}
        </template>
      </el-table-column>
       <el-table-column
        label="操作">
         <template v-slot="{row}">
            <el-button type="danger" size="mini" @click="Delarticle(row.id) ">删除</el-button>
         </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="q.pagenum"
      :page-sizes="[2,3 ,5 ,10 ]"
      :page-size="q.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <el-dialog
  title="文章预览"
  :visible.sync="acdialogVisible"
  width="80%"
  >
<h1 class="title"> {{particularsList.title}} </h1>
<div class="info">
 <span>作者：{{ particularsList.nickname || particularsList.username }}</span>
    <span>发布时间：{{formDate( particularsList.pub_date)}}</span>

    <span>所属分类：{{ particularsList.cate_name }}</span>
    <span>状态：{{ particularsList.state }}</span>
      <!-- 分割线 -->
  <el-divider></el-divider>

  <img :src="'http://www.liulongbin.top:3008' + particularsList.cover_img" alt="" />
  <div v-html="particularsList.content"></div>
</div>
</el-dialog>

    </el-card>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',

  data () {
    return {
      total: 0,
      getList: [],
      articleLists: [],
      particularsList: [],
      picture: '',
      dialogVisible: false,
      acdialogVisible: false,
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      ruleForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请至少选择一个类型', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]

      }
    }
  },
  created () {
    this.initList()
    this.newList()
  },
  methods: {
    handleClose (done) {
      this.$confirm('此操作将丢失文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done()
      }).catch(() => {})
    },
    async  initList () {
      const { data: res } = await this.$http.get('/my/cate/list')
      this.getList = res.data
    },
    getImg (e) {
      const file = e.target.files[0]
      if (file) {
        this.ruleForm.cover_img = file
        this.picture = URL.createObjectURL(file)
      } else {
        this.ruleForm.cover_img = ''
        this.picture = ''
      }
      this.$refs.ruleForm.validateField('cover_img')
    },
    hSubmit (state) {
      this.ruleForm.state = state
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        const fd = new FormData()
        Object.keys(this.ruleForm).forEach(k => fd.append(k, this.ruleForm[k]))
        const { data: res } = await this.$http.post('/my/article/add', fd)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.dialogVisible = false
        this.$refs.ruleForm.resetFields()
        this.newList()
        this.picture = ''
      })
    },
    async newList () {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      this.articleLists = res.data
      this.total = res.total
    },
    formDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSizeChange (size) {
      this.q.pagesize = size
      this.q.pagenum = 1
      this.newList()
    },
    handleCurrentChange (current) {
      this.q.pagenum = current
      this.newList()
    },
    filersort () {
      this.q.pagenum = 1
      this.newList()
    },
    replacement () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''

      }
      this.newList()
    },
    async  articleDetails (id) {
      const { data: res } = await this.$http.get('/my/article/info', {
        params: {
          id
        }
      })
      if (res.code !== 0) return
      this.acdialogVisible = true
      this.particularsList = res.data
      console.log(res.data)
    },
    // Delarticle (id) {
    //   this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(async () => {
    //     const { data: res } = await this.$http.delete('/my/article/info', {
    //       params: {
    //         id
    //       }
    //     })
    //     if (res.code !== 0) return this.$message.error(res.message)
    //     this.$message.success(res.message)
    //     if (this.articleLists.length === 1 && this.q.pagenum > 1) {
    //       this.q.pagenum--
    //     }

    //     this.newList()
    //   }).catch(() => {})
    // }

    // 利用async await方法
    async  Delarticle (id) {
      const confirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirm !== 'confirm') return
      const { data: res } = await this.$http.delete('/my/article/info', {
        params: {
          id
        }
      })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      if (this.articleLists.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
    }

  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }

}
 /deep/ .ql-editor{
    height: 300px;
}
.el-pagination {
  margin-top: 15px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
